package com.hongyi.common.mybatis.utils;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.hongyi.common.framework.exception.ServiceException;
import com.hongyi.common.framework.utils.spring.SpringUtils;
import com.hongyi.common.framework.utils.string.ConvertUtils;
import com.hongyi.common.mybatis.enums.DataBaseType;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库助手
 *
 * @author DingHao
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DateBaseUtils {

    /**
     * 获取自定义的数据源类
     */
    private static final DynamicRoutingDataSource DS = SpringUtils.getBean(DynamicRoutingDataSource.class);

    /**
     * 获取当前数据库类型
     */
    public static DataBaseType getDataBaseType() {
        DataSource dataSource = DS.determineDataSource();
        try (Connection conn = dataSource.getConnection()) {
            DatabaseMetaData metaData = conn.getMetaData();
            String databaseProductName = metaData.getDatabaseProductName();
            return DataBaseType.find(databaseProductName);
        } catch (SQLException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 数据库类型是否为MySql
     */
    public static boolean isMySql() {
        return DataBaseType.MY_SQL == getDataBaseType();
    }

    public static String findInSet(Object var1, String var2) {
        DataBaseType dataBasyType = getDataBaseType();
        String var = ConvertUtils.toStr(var1);
        if (dataBasyType == DataBaseType.MY_SQL) {
            return String.format("find_in_set('%s', %s) <> 0", var, var2);
        }
        return String.format("find_in_set('%s', %s) <> 0", var, var2);


    }

    /**
     * 获取当前加载的数据库名
     */
    public static List<String> getDataSourceNameList() {
        return new ArrayList<>(DS.getDataSources().keySet());
    }


}
